import React, { memo, useState, useRef, useEffect, createElement } from "react";
import { useHistory } from "react-router-dom";
import { MommentWrapper } from "./style";

import {
  Avatar,
  Tooltip,
  message,
  Empty,
  Comment,
  Pagination,
  Image,
} from "antd";
import { isToken } from "@/hooks";
import moment from "moment";

import {
  setMommentLove,
  setMommentComment,
  getMommentComment,
} from "@/service/discover";
import { Input, Button, Rate } from "antd";
import { Collapse } from "antd";
import axios from "axios";
import { handleComment, deDuplication } from "@/utils/comment";
import { CaretRightOutlined } from "@ant-design/icons";
import AskComment from "./comment";
import {
  DislikeOutlined,
  LikeOutlined,
  DislikeFilled,
  LikeFilled,
} from "@ant-design/icons";
import { number } from "prop-types";
import { TREE_HOLE_AVATAR } from "@/common/contants";
const { TextArea } = Input;
const { Panel } = Collapse;
export default memo(function AskDiscoverMomment(props) {
  const {
    mommentList = [],
    setPage,
    currentPage,
    userDetail,
    state,
    mommentTotal,
  } = props;
  const [commentValue, setcommentValue] = useState("");
  const [commentList, setcommentList] = useState({});
  const [currentAid, setcurrentAid] = useState(0);
  const [snapCommentList, setsnapCommentList] = useState({});
  const [isCommentEmpty, setisCommentEmpty] = useState(false);
  const [isReplyClick, setisReplyClick] = useState(false);

  const history = useHistory();
  const inputRef = useRef();
  const likeClick = async (article_id, islike) => {
    let token = await isToken();
    if (!token) {
      history.push("/login");
      return;
    }

    let obj = {
      article_id,
      islike,
      user_id: userDetail.id,
    };
    setMommentLove(obj).then((res) => {
      if (res.data.code) {
        message.warning("取消点赞或点踩!");
      } else {
        message.success("操作成功!");
      }
      state();
    });
  };
  // 获取兄弟元素 函数
  const sibling = (elm) => {
    var a = [];
    var p = elm.parentNode.children;
    for (var i = 0, pl = p.length; i < pl; i++) {
      if (p[i] !== elm) a.push(p[i]);
    }
    return a;
  };

  // 获取留言 函数
  const getComment = async (artid, isReply, num, setLike = false) => {
    let page;
    if (isReply) {
      page = num;
    } else {
      page = commentList[artid] ? commentList[artid].page : 1;
    }
    let obj = {
      page,
      size: 30,
      article_id: artid,
    };
    const res = await getMommentComment(obj);

    if (res.data.length > 0) {
      let newArr = handleComment(res.data, 1);
      let newComment = { ...commentList };
      let snapObj = { ...snapCommentList };

      if (newArr.length == 0) {
        setisCommentEmpty(true);
        if (newComment[artid] && newComment[artid].page) {
          if (!isReply && !setLike) {
            newComment[artid].page++;
          }
        } else {
          newComment[artid] = { list: [], page: 2 };
        }

        if (!snapObj[artid]) {
          snapObj[artid] = { list: [] };
        }
        snapObj[artid].list = deDuplication([
          ...res.data,
          ...snapObj[artid].list,
        ]);
        setsnapCommentList(snapObj);
        setcommentList(newComment);
      } else {
        setisCommentEmpty(false);
        newArr = newArr.reverse();
        if (!snapObj[artid]) {
          snapObj[artid] = { list: [] };
        }

        const arrs = deDuplication([...res.data, ...snapObj[artid].list]);
        snapObj[artid].list = deDuplication([
          ...res.data,
          ...snapObj[artid].list,
        ]);
        const arr1 = handleComment(arrs, 1);

        if (!newComment[artid]) {
          newComment[artid] = { list: [], page: 1 };
        }
        newComment[artid].list = deDuplication(arr1);
        newComment[artid].list.reverse();
        setcommentList(newComment);
        setsnapCommentList(snapObj);
      }
    }
  };

  useEffect(() => {
    if (isCommentEmpty == true) {
      getComment(currentAid);
    } else if (isReplyClick) {
      setisReplyClick(false);
      getComment(currentAid);
    }
  }, [commentList]);

  const commentClick = (e, artid) => {
    setcurrentAid(artid);
    setcommentValue("");
    let arr = sibling(e.currentTarget.parentNode)[2];

    if (arr.style.display == "block") {
      arr.style.display = "none";
    } else {
      arr.style.display = "block";
      if (!commentList[artid]) {
        getComment(artid);
      }
    }
  };

  const submitComment = async (id) => {
    let token = await isToken();
    if (!token) {
      history.push("/login");
      return;
    }

    let obj = {
      article_id: id,
      user_id: userDetail.id,
      comment_id: "0",
      content: commentValue,
      avatar: userDetail.avatarUrl,
      user_name: userDetail.nick,
    };

    const res = await setMommentComment(obj);
    if (res.data) {
      message.success("评论成功!");
      setcommentValue("");
      state();
      if (commentList[currentAid]) {
        await getComment(currentAid, true, 1);
      } else {
        getComment(currentAid);
      }
    }
  };
  const commentInput = (e) => {
    setcommentValue(e.target.value);
  };
  let timer = null;
  const loadMore = (artid) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      setisReplyClick(true);
      const obj = { ...commentList };
      obj[currentAid].page++;
      setcommentList(obj);
    }, 400);
  };
  const setCurrentTextFocusAid = (id) => {
    setcurrentAid(id);
  };
  const handleTextAreaFocus = (id) => {
    setCurrentTextFocusAid(id);
  };

  const pageChange = (page) => {
    setPage(page);
  };

  return (
    <MommentWrapper>
      <div className="content">
        {mommentList.map((item) => {
          return (
            <div key={item.id} className="item">
              <div className="top">
                <div className="avatar">
                  {item.cid == 3 ? (
                    <Avatar size={44} src={TREE_HOLE_AVATAR} />
                  ) : (
                    <Avatar size={44} src={item.avatar} />
                  )}
                </div>
                <div className="username">
                  <div className="name">
                    {item.cid == 3 ? (
                      <span>树洞￱robot</span>
                    ) : (
                      <span>{item.uname}</span>
                    )}
                  </div>
                  <div className="time">
                    {item.cid == 3 ? <span>自动匿名机器人 </span> : ""}
                    <span>发布:</span>
                    <Tooltip
                      title={moment(item.createAt).format(
                        "YYYY-MM-DD HH:mm:ss"
                      )}
                    >
                      <span>{moment(item.createAt).fromNow()}</span>
                    </Tooltip>
                  </div>
                </div>
              </div>

              <div className="bottom">
                <div
                  className="b-content"
                  dangerouslySetInnerHTML={{ __html: item.content }}
                ></div>

                <div className="imgs-box">
                  <Image.PreviewGroup>
                    {item.filepath &&
                      item.filepath.map((item) => {
                        return <Image key={item} width={203.3} height={144} src={item} />;
                      })}
                  </Image.PreviewGroup>
                </div>

                <div className="like">
                  <div className="2" onClick={() => likeClick(item.id, true)}>
                    <i className="iconfont icon-dianzan"></i>
                    <span> {item.love_num}</span>
                  </div>
                  <div
                    className="123"
                    onClick={(e) => commentClick(e, item.id)}
                  >
                    <i className="iconfont icon-pinglun"></i>
                    <span>{item.comment_num}</span>
                  </div>
                  <div className="3" onClick={() => likeClick(item.id, false)}>
                    <i className="iconfont icon-dislike"></i>
                    <span>{item.hate_num}</span>
                  </div>
                </div>

                <div ref={inputRef} className="comments">
                  <div>
                    <TextArea
                      bordered={false}
                      className="text-area"
                      allowClear={true}
                      value={commentValue}
                      rows={2}
                      onFocus={() => handleTextAreaFocus(item.id)}
                      onChange={(e) => commentInput(e)}
                      placeholder="留下友善的评论吧!"
                    />
                    <div className="submit-box">
                      <Button
                        onClick={() => submitComment(item.id)}
                        type="primary"
                        className="submit-btn"
                      >
                        提交回复
                      </Button>
                    </div>
                    <div className="comment-num">
                      全部评论({item.comment_num})
                    </div>
                    <div className="comment-list">
                      {commentList.hasOwnProperty(item.id) ? (
                        <div>
                          {commentList[item.id].list.map((item2) => {
                            return (
                              <AskComment
                                setCurrentTextFocusAid={setCurrentTextFocusAid}
                                commentList={commentList}
                                getComment={getComment}
                                userDetail={userDetail}
                                key={item2.id}
                                uid={item.uid}
                                item={item2}
                                state={state}
                              ></AskComment>
                            );
                          })}

                          <div>
                            {
                              <div className="loadMore">
                                {snapCommentList[item.id] &&
                                snapCommentList[item.id].list.length <
                                  item.comment_num ? (
                                  <Button
                                    onClick={() => loadMore(item.id)}
                                    size="small"
                                  >
                                    点击加载更多评论...
                                  </Button>
                                ) : (
                                  <div>
                                    <Empty
                                      description="暂无更多评论数据!"
                                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                                    />
                                  </div>
                                )}
                              </div>
                            }
                          </div>
                        </div>
                      ) : (
                        <div>
                          <div>
                            <Empty
                              description="暂无评论数据,快去评论吧!"
                              image={Empty.PRESENTED_IMAGE_SIMPLE}
                            />
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
        <div className="m-pagination">
          <Pagination
            total={mommentTotal}
            showSizeChanger={false}
            showQuickJumper
            pageSize={15}
            onChange={(e) => pageChange(e)}
            showTitle
            defaultCurrent={1}
            hideOnSinglePage
            current={currentPage}
          />
        </div>
      </div>
    </MommentWrapper>
  );
});
